import * as THREE from "three";
import { EffectComposer } from "three/addons/postprocessing/EffectComposer.js";
import { RenderPass } from "three/addons/postprocessing/RenderPass.js";
import { ShaderPass } from "three/addons/postprocessing/ShaderPass.js";
import { OutlinePass } from "three/addons/postprocessing/OutlinePass.js";
import { FXAAShader } from "three/addons/shaders/FXAAShader.js";

/**
 * 创建后处理边框高亮效果
 * @param {THREE.Scene} scene - 场景对象
 * @param {THREE.Camera} camera - 相机对象
 * @param {THREE.Renderer} renderer - 渲染器对象
 * @returns {Object} 包含后处理相关对象的配置
 */
export function createOutlinePostProcessing(scene, camera, renderer, container) {
  // 创建效果合成器
  const composer = new EffectComposer(renderer);
  // 添加渲染通道（基础场景渲染）
  const renderPass = new RenderPass(scene, camera);
  composer.addPass(renderPass);

  // 创建一个空数组用于存储需要高亮的对象
  const selectedObjects = [];

  // 创建轮廓通道
  const outlinePass = new OutlinePass(new THREE.Vector2(container.value.clientWidth, container.value.clientHeight), scene, camera, selectedObjects);
  // 设置边框颜色（这里使用亮黄色）
  outlinePass.visibleEdgeColor.set(0xffffff);
  outlinePass.hiddenEdgeColor.set(0x190a05);
  // 配置轮廓效果
  outlinePass.edgeStrength = 3.0; // 边框强度
  outlinePass.edgeGlow = 1; // 边框发光程度
  outlinePass.edgeThickness = 1; // 边框厚度
  outlinePass.usePatternTexture = false; // 是否使用图案纹理

  // 添加轮廓通道到合成器
  composer.addPass(outlinePass);

  // 添加抗锯齿通道
  const fxaaPass = new ShaderPass(FXAAShader);
  fxaaPass.material.uniforms["resolution"].value.set(1 / container.value.clientWidth, 1 / container.value.clientHeight);
  composer.addPass(fxaaPass);

  // 用于切换对象高亮状态的函数
  function toggleOutline(object) {
    // if (selectedObjects.includes(object)) {
    //   // 移除高亮
    //   const index = selectedObjects.indexOf(object);
    //   selectedObjects.splice(index, 1);
    // } else {
    //   // 添加高亮
    //   selectedObjects.push(object);
    // }

    // 更新轮廓通道
    // outlinePass.selectedObjects = selectedObjects;
    outlinePass.selectedObjects = [object];
  }

  // 用于更新后处理尺寸的函数
  function onWindowResize() {
    const width = container.value.clientWidth;
    const height = container.value.clientHeight;
    composer.setSize(width, height);
    // 更新FXAA抗锯齿的分辨率
    fxaaPass.material.uniforms["resolution"].value.set(1 / width, 1 / height);
  }

  return {
    composer,
    outlinePass,
    selectedObjects,
    toggleOutline,
    onWindowResize
  };
}
